function AllReady() {
  var mstform = Ext.getCmp("CntChangeM7"); //获取容器
  var tabPanel = Ext.getCmp("tabPanel"); // 获取当前所在 tab 页
  var dgrid = Ext.getCmp("CntChangeD7"); // 获取当前所在 tab 页
  var PhidCnt = mstform.queryById("PhidCnt");
  var PhidPc = mstform.queryById("PhidPc");
  var user_division = mstform.queryById("user_division"); //获取字段---事业部
  var user_regional_center = mstform.queryById("user_regional_center"); //区域中心
  var OriPhidDept = mstform.queryById("OriPhidDept");
  var PhidBuyer = mstform.queryById("PhidBuyer");
  var user_ywlx = mstform.queryById("user_ywlx");
  var user_product_line = mstform.queryById("user_product_line");
  var user_pro_type = mstform.queryById("user_pro_type ");
  var user_business_type = mstform.queryById("user_business_type");
  var user_purchaser = mstform.queryById("user_purchaser");
  var OriCntTitle = mstform.queryById("OriCntTitle");
  var Title = mstform.queryById("Title");
  var toolbar = Ext.getCmp("toolbar");
  var dstore = dgrid.store;
  toolbar.get("imp").setText("引用采购合同");
  // var dstore2 = dgrid2.store;
  // console.log(dstore2);
  //  隐藏合同条款删除按钮
  (['add','edit','view'].includes(otype))&&hidenDeleteBtn()
  function hidenDeleteBtn(){
    window.isDeleteLock = setInterval(()=>{
      try{
        if(document.querySelector("#itemtab-body")){
          const element = seachId("itemtab-body",[0,0,0,0,0,0])
          const Box = Ext.getCmp(element)
          Box.queryById("deleterow").hide()
          clearInterval(window.isDeleteLock)
        }
        
      }catch(err){
      }
    },1000)
  }
  function seachId(id,arr){
    let element = document.getElementById(id)
    arr.forEach(item=>{
      element = document.getElementById(element.children[item].id)
    })
    return element.id
  }
  //给表体默认值
  Title.setValue("采购合同变更");
  Title.hide();
  ////////////////////////////////
  var dgrid3 = Ext.getCmp("itemtab").items;
  console.log(dgrid3);
  
  ///////////////////////////////////
  if (otype == $Otype.ADD || otype == $Otype.EDIT || otype == $Otype.COPY) {
    getCntPtypeparam();
    PhidCnt.addListener("helpselected", function () {
      getCntPtypeparam();
    });
    dstore.on("datachanged", async function (dstore, eOpts) {
      const records = dstore.getRange();
      for (const record of records) {
        try {
          if (record.data.QtyNew > record.data.QtyOld) {
            record.set("QtyNew", record.data.QtyOld);
            Ext.Msg.alert("提示", "新采购数量不能大于原采购数量");
          }
        } catch (error) {
          // console.error(error);
        }
      }
    });
  }

  if (mstform) {
    if (PhidPc.getValue()) {
      // console.log("PhidPc", PhidPc.getValue());
      execServer("getPtInfoByPhid", { phid: PhidPc.getValue() }, function (res) {
        const datas = JSON.parse(res.data)[0].extendObjects;
        //帮助字段赋值
        // console.log(datas, "datas");
        user_division.setValue(datas.division_phid);
        user_product_line.setValue(datas.midwife_phid);
        user_regional_center.setValue(datas.regional_center_phid);
        BatchBindCombox([user_division]);
        BatchBindCombox([user_product_line]);
        BatchBindCombox([user_regional_center]);
      });
    }
  }
  OriCntTitle.addListener("change", function (args) {
    Title.setValue(OriCntTitle.getValue());
  });
  PhidCnt.addListener("helpselected", function () {
      getYhdQtyByCntPhidAndItem()
    execServer("getCntInfo", { cnt: PhidCnt.getValue() }, function (res) {
      execServer("getCntInfo", { cnt: PhidCnt.getValue() }, function (res) {
        const datasGetCntInfo = JSON.parse(res.data)[0].extendObjects;
        if (datasGetCntInfo) {
          if (datasGetCntInfo.pc) {
            PhidPc.setValue(datasGetCntInfo?.pc);
            BatchBindCombox([PhidPc]);
          }
          if (datasGetCntInfo.upt) {
            user_pro_type.setValue(datasGetCntInfo.upt);
          }
          if (datasGetCntInfo.ubt) {
            // user_ywlx.setValue(datasGetCntInfo.ubt);
            // BatchBindCombox([user_ywlx]);
          }
          if (datasGetCntInfo.up) {
            user_purchaser.setValue(datasGetCntInfo.up);
            BatchBindCombox([user_purchaser]);
          }
        }
      });
    });
  });
  PhidPc.addListener("change", function (args) {
    if (PhidPc.getValue()) {
      execServer("getPtInfoByPhid", { phid: PhidPc.getValue() }, function (res) {
        const datas = JSON.parse(res.data)[0].extendObjects;
        //帮助字段赋值
        // console.log(datas, "datas");
        user_division.setValue(datas.division_phid);
        user_product_line.setValue(datas.midwife_phid);
        user_regional_center.setValue(datas.regional_center_phid);
        BatchBindCombox([user_division]);
        BatchBindCombox([user_product_line]);
        BatchBindCombox([user_regional_center]);
      });
      if (!PhidCnt.getValue()) return;
      execServer("getCntMInfoByPhid", { phid: PhidCnt.getValue() }, function (res) {
        try {
          const datasGetCntMInfoByPhid = JSON.parse(res.data)[0].extendObjects;
          //帮助字段赋值
          // console.log(datasGetCntMInfoByPhid, "getCntMInfoByPhid");
          OriPhidDept.setValue(datasGetCntMInfoByPhid.dept_phid);
          BatchBindCombox([OriPhidDept]);
          // user_gys.setValue(datasGetCntMInfoByPhid.supply_id);
          // BatchBindCombox([user_gys]);
        } catch (error) {}
      });
    }
  });
  var dgrid = Ext.getCmp("CntChangeD7");
  var dstore = dgrid.store;
  dgrid.getStore().on('datachanged', async function (dstore, eOpts) {
      const records = dstore.getRange();
      for (const record of records) {
          if(record.get("PhidItemdata")){
              if (window._catch_wl_info_qty) {
                
                let _temp = window._catch_wl_info_qty.filter((el)=>{
                    if(el.phid_itemdata == record.get("PhidItemdata")){
                        return el
                    }
                })
              
              if(_temp.lenth != 0){
                  _temp = _temp[0]
                  console.log(`调试是否进入`,_temp);
                  record.set("user_yyhsl", _temp.qty)
                  let oriprc = record.get('PrcOldVatFc')
                  let newprc = record.get('PrcNewFc')
                  if (newprc>oriprc) {
                    Ext.Msg.alert("提示", "新未税单价不能大于原未税单价");
                    record.set("PrcNewFc",record.data.PrcOldVatFc)
                  }
                  let QtyNew = record.get("QtyNew")
                  if(QtyNew<_temp.qty){
                      Ext.Msg.alert("提示", "新采购数量不能小于已要货数量");
                      record.set("QtyNew",record.data.QtyOld)
                  }
                  QtyNew = record.get("QtyNew")
                  record.set("user_yhsyl", QtyNew - _temp.qty)
              } else {
                  record.set("user_yhsyl", 0)
                  record.set("user_yyhsl", 0)
              }
            }
            }
      }
      dgrid.getView().refresh()
  })
  dgrid.addListener("edit", function (editor, e) {
    var record = e.record;
    if (e.originalValue == e.value) {
      return;
    }
    console.log(`调试缓存检查debug`, window._catch_wl_info_qty);
    console.log(`调试当前物料debug`, record.get("PhidItemdata"));
    // 取出当前物料的要货量
    if(record.get("PhidItemdata")){
      if (window._catch_wl_info_qty) {
      let _temp = window._catch_wl_info_qty.filter((el)=>{
          if(el.phid_itemdata == record.get("PhidItemdata")){
              return el
          }
      })
      let user_yyhsl = record.get("user_yyhsl");
      let QtyNew = record.get("QtyNew");
          let oriprc = record.get('PrcOldVatFc')
          let newprc = record.get('PrcNewVatFc')
          if (newprc>oriprc) {
            Ext.Msg.alert("提示", "新含税单价不能大于原含税单价");
              record.set("PrcNewVatFc",oriprc)
          }
          if(QtyNew<user_yyhsl){
              Ext.Msg.alert("提示", "新采购数量不能小于已要货数量");
              record.set("QtyNew",record.data.QtyOld)
          }
          dgrid.getView().refresh()
      // if(_temp.lenth != 0){
      //     _temp = _temp[0]
      //     console.log(`调试是否进入`,_temp);
      //     record.set("user_yyhsl", _temp.qty)
      //     let QtyNew = record.get("QtyNew");
      //     let oriprc = record.get('PrcOldVatFc')
      //     let newprc = record.get('PrcNewFc')
      //     if (newprc>oriprc) {
      //       Ext.Msg.alert("提示", "新未税单价不能大于原未税单价");
      //       record.set("PrcNewFc",record.data.PrcOldVatFc)
      //     }
      //     if(QtyNew<_temp.qty){
      //         Ext.Msg.alert("提示", "新采购数量不能小于已要货数量");
      //         record.set("QtyNew",record.data.QtyOld)
      //     }
      //     QtyNew = record.get("QtyNew")
      //     record.set("user_yhsyl", QtyNew - _temp.qty)
      // } else {
      //     record.set("user_yhsyl", 0)
      //     record.set("user_yyhsl", 0)
      // }
    }
    }
    try {
      if (record.data.QtyNew > record.data.QtyOld) {
        record.set("QtyNew", record.data.QtyOld);
        Ext.Msg.alert("提示", "新采购数量不能大于原采购数量");
      }
    } catch (error) {
      console.error(error);
    }
    dgrid.getView().refresh()
  });
// 根据合同获取要货单物料的使用量
getYhdQtyByCntPhidAndItem()
function getYhdQtyByCntPhidAndItem(){
  const cnt = mstform.queryById("PhidCnt").getValue()
  if(!cnt) return
  execServer("getYhdQtyByCntPhidAndItem",{cnt},(res)=>{
      if(res.count == 0) return
      window._catch_wl_info_qty = JSON.parse(res.data).reduce((value,item)=>{
          value.push(item.extendObjects)
          return value
      },[])
  })
}
  //根据id获取原合同条款信息
  function getCntPtypeparam() {
    console.log("getCntPtypeparam");
    const phidCntV = PhidCnt.getValue();

    if (!phidCntV) return;

    tabPanel.setActiveTab(1);
    var dgrid3 = Ext.getCmp("itemtab").items.items[0].items.items[0];
      console.log(phidCntV);
      
    execServer("getCntPtypeparam", { phid_cnt: phidCntV }, function (res) {
      console.log(res);
      if (res.count > 0) {
        const datas = JSON.parse(res.data);
        console.log(datas);
        var gridArr = [];
        var gridCount = res.count;
        for (var i = 0; i < gridCount; i++) {
          var gridObj = {};
          gridObj.PhidRelItem = datas[i].extendObjects.phid;
          gridObj.PhidItem = datas[i].extendObjects.phid_item;
          gridObj.PhidItemNew = datas[i].extendObjects.phid_item_new;
          gridObj.Name = datas[i].extendObjects.name;
          gridObj.NameNew = datas[i].extendObjects.name_new;
          gridObj.user_zffs = datas[i].extendObjects.user_zffs;
          gridObj.user_bghzffs = datas[i].extendObjects.user_zffs;
          gridObj.user_xzzq = datas[i].extendObjects.user_xzzq;
          gridObj.user_bghxzzq = datas[i].extendObjects.user_xzzq;
          gridObj.user_zbqs_dt = datas[i].extendObjects.user_zbqs_dt;
          gridObj.user_bghzbqssj = datas[i].extendObjects.user_zbqs_dt;
          gridObj.user_hp_dt = datas[i].extendObjects.user_hp_dt;
          gridObj.user_bghhpsj = datas[i].extendObjects.user_hp_dt;
          gridObj.user_fktj = datas[i].extendObjects.user_fktj;
          gridObj.user_bghfktj = datas[i].extendObjects.user_fktj;
          gridObj.user_zfjsjs = datas[i].extendObjects.user_zfjsjs;
          gridObj.user_bghzfjsjs = datas[i].extendObjects.user_zfjsjs;
          gridObj.BalPercent = datas[i].extendObjects.bal_percent;
          gridObj.BalPercentNew = datas[i].extendObjects.bal_percent;

          // gridObj.oper_flg = datas[i].extendObjects.oper_flg;
          gridArr.push(gridObj);
        }
        dgrid3.store.add(gridArr);
        // console.log(gridArr);
      } else {
        console.log("功能扩展暂无数据");
      }
    });

    tabPanel.setActiveTab(0);
  }
}
function beforeSaveEdit() {
  // 1. 获取稳定的父容器（根据ID）
  const parentTab = document.getElementById('itemtab');
  if (!parentTab) {
      // alert("错误：主容器未找到");
      // return false;
  }

  // 2. 逐层定位目标网格（假设结构为 div → div → span → div → 目标网格）
  const targetGrid = parentTab
      .querySelector('#itemtab-body') // 第一层子容器
      ?.querySelector('div > div > span > div') // 层级路径
      ?.querySelector('div.x-grid:first-child'); // 目标网格（假设类名包含 x-grid）

  // 3. 验证是否找到有效网格
  if (!targetGrid) {
      // alert("错误：支付比例网格未找到");
      // return false;
  }

  // 4. 获取 ExtJS 组件实例（通过 Ext.getCmp 或 DOM 关联）
  const extGrid = Ext.getCmp(targetGrid.id); // 依赖 ExtJS 的 DOM 关联
  if (!extGrid || !extGrid.store) {
      // alert("错误：网格数据未初始化");
      // return false;
  }
  if (!extGrid.store || extGrid.store.getCount() === 0) {
    return true; // 无数据直接放行
  }
  // 5. 计算总和（处理浮点精度）
  let totalBfb = 0;
  extGrid.store.each(item => {
      const val = Ext.Number.from(item.get('BalPercentNew'), 0);
      totalBfb = +(totalBfb + val).toFixed(4); // 保留四位小数
  });

  // 6. 校验逻辑
  if (Math.abs(totalBfb - 1) > 0.001) {
    Ext.Msg.alert("提示",`变更后合同支付比例总和为 ${(totalBfb * 100).toFixed(2)}%，请调整为100%`);
      return false;
  }

  return true;
}